<script setup lang="ts" name="InfraResourceConfig">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { dateTimeFormatter } from '@/utils/dateUtil'
import { fileSizeFormatter } from '@/utils/file/helper'
import { ResourceConfigApi } from '@/api/infra/resource/config'
import { dataToFile } from '@/components/Excel/src/helper'
import ResourceConfigForm from './ResourceConfigForm.vue'
import { checkPermit, computedOperateWidth } from '@/utils/permit'
import { getIntDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const total = ref(0) // 列表的总页数
const list = ref([]) // 表格数据
const queryLoading = ref(false) // 列表加载中：1）列表数据加载；2）查询按钮禁用；3）重置按钮禁用
const queryParams = ref({
  pageIndex: 1,
  pageSize: 20,
  name: undefined,
  storage: undefined,
  create_time: undefined
})
const queryFormRef = ref() // 搜索的表单


/** 查询列表 */
const getList = async () => {
  queryLoading.value = true
  try {
    const data = await ResourceConfigApi.page(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    queryLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageIndex = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.pageIndex = 1
  queryParams.value.pageSize = 20
  queryParams.value.name = undefined
  queryParams.value.storage = undefined
  queryParams.value.create_time = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ResourceConfigApi.delete(id)
    message.success(t('message.del', 'success'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 主配置按钮操作 */
const handleMaster = async (id) => {
  try {
    await message.confirm(t('infra.resource.config.rules', 'master', [id]))
    await ResourceConfigApi.updateMaster(id)
    message.success(t('message', 'updateSuccess'))
    await getList()
  } catch {}
}

/** 测试按钮操作 */
const handleTest = async (id) => {
  try {
    await ResourceConfigApi.test(id)
    message.success(t('infra.resource.config', 'success'))
  } catch {}
}

const ExcelExportDialogRef = ref()

const filedList = ref([
  { key: 'id', value: 'ID' },
  { key: 'name', value: t('infra.resource.config', 'name') },
  { key: 'storage', value: t('infra.resource.config', 'storage') },
  { key: 'master', value: t('infra.resource.config', 'master') },
  { key: 'basePath', value: t('infra.resource.config', 'basePath') },
  { key: 'host', value: t('infra.resource.config', 'host') },
  { key: 'port', value: t('infra.resource.config', 'port') },
  { key: 'username', value: t('infra.resource.config', 'username') },
  { key: 'password', value: t('infra.resource.config', 'password') },
  { key: 'mode', value: t('infra.resource.config', 'mode') },
  { key: 'endpoint', value: t('infra.resource.config', 'endpoint') },
  { key: 'bucket', value: t('infra.resource.config', 'bucket') },
  { key: 'accessKey', value: t('infra.resource.config', 'accessKey') },
  { key: 'accessSecret', value: t('infra.resource.config', 'accessSecret') },
  { key: 'domain', value: t('infra.resource.config', 'domain') },
  { key: 'imageExts', value: t('infra.resource.config', 'imageExts') },
  { key: 'videoExts', value: t('infra.resource.config', 'videoExts') },
  { key: 'audioExts', value: t('infra.resource.config', 'audioExts') },
  { key: 'textExts', value: t('infra.resource.config', 'textExts') },
  { key: 'applicationExts', value: t('infra.resource.config', 'applicationExts') },
  { key: 'imageSize', value: t('infra.resource.config', 'imageSize') },
  { key: 'videoSize', value: t('infra.resource.config', 'videoSize') },
  { key: 'audioSize', value: t('infra.resource.config', 'audioSize') },
  { key: 'textSize', value: t('infra.resource.config', 'textSize') },
  { key: 'applicationSize', value: t('infra.resource.config', 'applicationSize') },
  { key: 'create_time', value: t('common', 'createTime') },
  { key: 'remark', value: t('common', 'remark') }
])
/** 导出按钮操作 */
const handleExport = async () => {
  ExcelExportDialogRef.value.open()
}

const exportDone = async (res) => {
  if (res.dataScope === 1) {
    dataToFile(list.value, res)
  } else if (res.dataScope === 3) {
    const allList = await ResourceConfigApi.export(queryParams.value)
    dataToFile(allList, res)
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<template>
  <PageCard>
    <ContentFormTable>
      <template #header>
        <ElForm ref="queryFormRef" :model="queryParams" :inline="true">
          <ElFormItem :label="t('infra.resource.config', 'name')" prop="name" class="!w-240px">
            <el-input v-model="queryParams.name" :placeholder="t('infra.resource.config.rules', 'name')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem :label="t('infra.resource.config', 'storage')" prop="storage" class="!w-240px">
            <el-select v-model="queryParams.storage" :placeholder="t('infra.resource.config.rules', 'storage')" clearable class="!w-240px">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.INFRA_FILE_STORAGE)" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </ElFormItem>
          <ElFormItem :label="t('common', 'createTime')" prop="create_time">
            <el-date-picker
              v-model="queryParams.create_time"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              clearable
              :start-placeholder="t('common', 'startDate')"
              :end-placeholder="t('common', 'endDate')"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleQuery" />
          </ElFormItem>
          <ElFormItem>
            <el-button type="primary" :disabled="queryLoading" icon="Search" @click="handleQuery">{{ t('action', 'search') }}</el-button>
            <el-button icon="Refresh" :disabled="queryLoading" @click="resetQuery">{{ t('action', 'reset') }}</el-button>
            <el-button v-if="checkPermit(['infra:resource-config:create'])" type="success" icon="Plus" @click="openForm('create')">{{ t('action', 'create') }}</el-button>
            <CButton v-if="checkPermit(['infra:resource-config:export'])" type="warning" :disabled="queryLoading" :onClick="handleExport" preIcon="ri:export-line" :title="t('action', 'export')" />
          </ElFormItem>
        </ElForm>
      </template>
      <template #content>
        <el-table v-loading="queryLoading && systemConfig.loadingType === 'module'" :data="list" border>
          <el-table-column prop="id" :label="t('common', 'id')" align="center" />
          <el-table-column prop="name" :label="t('infra.resource.config', 'name')" show-overflow-tooltip min-width="140" align="center" />
          <el-table-column :label="t('infra.resource.config', 'storage')" align="center" prop="storage" width="120">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.INFRA_FILE_STORAGE" :value="scope.row.storage" />
            </template>
          </el-table-column>
          <el-table-column prop="remark" :label="t('common', 'remark')" show-overflow-tooltip align="center" min-width="200" />
          <el-table-column :label="t('infra.resource.config', 'master')" align="center" prop="primary" min-width="80">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.master" />
            </template>
          </el-table-column>
          <el-table-column prop="imageExts" :label="t('infra.resource.config', 'imageExts')" show-overflow-tooltip align="center" min-width="140" />
          <el-table-column prop="imageSize" :label="t('infra.resource.config', 'imageSize')" :formatter="fileSizeFormatter" align="center" min-width="140" />
          <el-table-column prop="videoExts" :label="t('infra.resource.config', 'videoExts')" show-overflow-tooltip align="center" min-width="140" />
          <el-table-column prop="videoSize" :label="t('infra.resource.config', 'videoSize')" :formatter="fileSizeFormatter" align="center" min-width="140" />
          <el-table-column prop="audioExts" :label="t('infra.resource.config', 'audioExts')" show-overflow-tooltip align="center" min-width="140" />
          <el-table-column prop="audioSize" :label="t('infra.resource.config', 'audioSize')" :formatter="fileSizeFormatter" align="center" min-width="140" />
          <el-table-column prop="textExts" :label="t('infra.resource.config', 'textExts')" show-overflow-tooltip align="center" min-width="140" />
          <el-table-column prop="textSize" :label="t('infra.resource.config', 'textSize')" :formatter="fileSizeFormatter" align="center" min-width="140" />
          <el-table-column prop="applicationExts" :label="t('infra.resource.config', 'applicationExts')" show-overflow-tooltip align="center" min-width="140" />
          <el-table-column prop="applicationSize" :label="t('infra.resource.config', 'applicationSize')" :formatter="fileSizeFormatter" align="center" min-width="140" />
          <el-table-column prop="create_time" :label="t('common', 'createTime')" :formatter="dateTimeFormatter" align="center" width="180" />
          <el-table-column
            v-if="checkPermit(['infra:resource-config:update', 'infra:resource-config:delete', 'infra:resource-config:update-master', 'infra:resource-config:test'])"
            prop="operate"
            :label="t('common', 'operate')"
            :width="computedOperateWidth(['infra:config:update', 'infra:config:delete', 'infra:resource-config:update-master', 'infra:resource-config:test'])"
            align="center"
            fixed="right">
            <template #default="scope">
              <el-button v-if="checkPermit(['infra:resource-config:update'])" type="primary" icon="Edit" @click="openForm('update', scope.row.id)" />
              <el-button v-if="checkPermit(['infra:resource-config:delete'])" type="danger" :disabled="scope.row.master" icon="Delete" @click="handleDelete(scope.row.id)" />
              <CTextButton v-if="checkPermit(['infra:resource-config:update-master'])" type="primary" :disabled="scope.row.master" preIcon="ri:fire-line" :title="t('infra.resource.config', 'master')" @click="handleMaster(scope.row.id)" />
              <CTextButton v-if="checkPermit(['infra:resource-config:test'])" type="primary" preIcon="ri:links-line" :title="t('action', 'test')" @click="handleTest(scope.row.id)" />
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageIndex" :total="total" :disabled="queryLoading" @pagination="getList" />
        <ResourceConfigForm ref="formRef" @success="getList" />
        <ExcelExportDialog ref="ExcelExportDialogRef" :filename="t('infra.resource.config', 'title')" :hasSelected="false" :fieldList="filedList" @success="exportDone" />
      </template>
    </ContentFormTable>
  </PageCard>
</template>

<style scoped lang="scss">
.el-table {
  width: 100%;
  height: 100%;
}
</style>
